﻿using System;
using System.Threading.Tasks;
using System.Windows.Input;
using Caliburn.Micro;

namespace MvvmEx.Base
{
    /// <summary>
    /// 可编辑节点
    /// </summary>
    public class CanEditTreeNodeViewModelBase : TreeNodeViewModelBase
    {
        #region 字段
        private string _editText;
        private bool _isFocus;

        #endregion

        #region 属性

        public bool IsFocus
        {
            get
            {
                return _isFocus;
            }
            set
            {
                if (value == _isFocus) return;
                _isFocus = value;
                NotifyOfPropertyChange(() => IsFocus);
            }
        }

        public string EditText
        {
            get
            {
                return _editText;
            }
            set
            {
                if (value == _editText) return;
                _editText = value;
                NotifyOfPropertyChange(() => EditText);
            }
        }
        #endregion

        #region 委托

        /// <summary>
        /// 修改名称委托
        /// </summary>
        public Func<string, Task<string>> NameChangedAction { get; set; }

        #endregion

        #region 失去焦点

        public void LostFocusCommand()
        {
            this.IsEdit = false;
            IsFocus = false;
        }

        #endregion

        #region 回车确认名称

        public async void EnterNameCommand(ActionExecutionContext context)
        {
            var e = context.EventArgs as KeyEventArgs;

            if (e != null)
            {
                if (e.Key == Key.Enter)
                {
                    if (NameChangedAction != null)
                    {
                        DisplayName = await NameChangedAction?.Invoke(EditText);
                    }
                    else
                    {
                        DisplayName = EditText;
                    }

                    this.IsEdit = false;
                }
            }
        }

        #endregion

        #region 私有方法

        #region 编辑节点名称

        protected void EditTreeNodeName(TreeNodeViewModelBase treeNode)
        {
            EditText = DisplayName;
            treeNode.IsEdit = true;
            IsFocus = true;
        }

        #endregion

        #endregion
    }
}